package tsj.ai.alibaba.data.analysis.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.document.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import tsj.ai.alibaba.data.analysis.common.connector.config.DbConfig;
import tsj.ai.alibaba.data.analysis.common.request.AgentSearchRequest;
import tsj.ai.alibaba.data.analysis.common.request.SchemaInitRequest;
import tsj.ai.alibaba.data.analysis.constant.Constant;
import tsj.ai.alibaba.data.analysis.entity.Datasource;
import tsj.ai.alibaba.data.analysis.service.datasource.DatasourceService;
import tsj.ai.alibaba.data.analysis.service.vectorstore.AgentVectorStoreService;
import tsj.ai.alibaba.data.analysis.util.SchemaProcessorUtil;

import java.util.List;
import java.util.Map;

import static tsj.ai.alibaba.data.analysis.constant.Constant.AGENTId;

/**
 * @author taoshujian
 * @version 1.0
 * @since 2025-11-14 16:29:53
 */
@Slf4j
@RestController
@RequestMapping("/api/vector")
public class VectorController {

    @Autowired
    private DatasourceService datasourceService;
    @Autowired
    private AgentVectorStoreService vectorStoreService;
    @Value("${spring.ai.vectorstore.agent-query-topk-limit:25}")
    protected int agentQueryTopkLimit;

    /**
     * 初始化数据源
     */
    @PostMapping("/init")
    public void initSchema() throws Exception {
        Datasource datasource = datasourceService.getDatasourceById(3L);
        // Create database configuration
        DbConfig dbConfig = SchemaProcessorUtil.createDbConfigFromDatasource(datasource);

        // Create SchemaInitRequest
        List<String> tables = List.of("products","orders","categories","order_items","product_categories","users");
        SchemaInitRequest schemaInitRequest = new SchemaInitRequest();
        schemaInitRequest.setDbConfig(dbConfig);
        schemaInitRequest.setTables(tables);

        log.info("Created SchemaInitRequest for dbConfig: {}, tables: {}", dbConfig, tables);
        log.info("Datasource details: id={}, name={}, host={}, port={}, databaseName={}, username={}, password=***", 
                datasource.getId(), datasource.getName(), datasource.getHost(), datasource.getPort(), 
                datasource.getDatabaseName(), datasource.getUsername());

        // Call the original initialization method
        try {
            vectorStoreService.schema(AGENTId, schemaInitRequest);
        } catch (Exception e) {
            log.error("Failed to initialize schema: {}", e.getMessage(), e);
            throw e;
        }
    }

    @PostMapping("/search")
    public void search(@RequestParam(value = "query", defaultValue = "去年销量最高的商品", required = false) String query) throws Exception {
        AgentSearchRequest searchRequest = AgentSearchRequest.getInstance(1+"");
        searchRequest.setQuery(query);
        searchRequest.setTopK(agentQueryTopkLimit);
        searchRequest.setMetadataFilter(Map.of(Constant.VECTOR_TYPE, Constant.COLUMN));
        List<Document>  documents = vectorStoreService.search(searchRequest);
        log.info("查询的向量: {}个", documents);
        for(Document document: documents){
            log.info("文档内容: {}", document.toString());
        }
    }

    @PostMapping("/findAll")
    public void findAll() throws Exception {
        List<Document>  documents = vectorStoreService.findAllDocuments();
        log.info("查询的向量: {}个", documents);
        for(Document document: documents){
            log.info("文档内容: {}", document.toString());
        }
    }
}